package com.zxm.oss.service.impl;

import com.zxm.common.core.domain.AjaxResult;
import com.zxm.oss.config.MinioConfigProperties;
import com.zxm.oss.enums.FilePathEnum;
import com.zxm.oss.utils.MinioUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * minio上传策略
 *
 * @author silencezheng
 * @date 2022/07/28
 */
@Service("minioUploadStrategyImpl")
public class MinioUploadStrategyImpl extends AbstractUploadStrategyImpl {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private MinioConfigProperties minioConfigProperties;
	@Autowired
	MinioUtil minioUtil;

	@Override
	public Boolean exists(String filePath) {
		return true;
	}
	@Override
	public void upload(String path, String fileName, InputStream inputStream) {}

	@Override
	public String getFileAccessUrl(String filePath) {
		System.out.println(minioConfigProperties.getUrl() + filePath);
		return minioConfigProperties.getUrl() + filePath;
	}

	@Override
	public String saveFile(MultipartFile uploadFile) {
		try {
			minioUtil.createBucket(minioConfigProperties.getBucket());
			minioUtil.uploadFile(uploadFile.getInputStream(), minioConfigProperties.getBucket(), FilePathEnum.PHOTO.getPath()+uploadFile.getOriginalFilename());
			return minioConfigProperties.getUrl()+minioConfigProperties.getBucket()+"/"+FilePathEnum.PHOTO.getPath()+uploadFile.getOriginalFilename();
		} catch (Exception e) {
			logger.error("上传文件失败", e);
		}
		return null;
	}

	/**
	 * 列出所有的桶
	 */
	public AjaxResult listBuckets() throws Exception {
		return AjaxResult.success(minioUtil.listBuckets());
	}

	/**
	 * 递归列出一个桶中的所有文件和目录
	 */
	public AjaxResult listFiles(String bucket) throws Exception {
		return AjaxResult.success("200", minioUtil.listFiles(bucket));
	}

	/**
	 * 下载一个文件
	 */
	public void downloadFile(String bucket, String objectName,
							 HttpServletResponse response) throws Exception {
		InputStream stream = minioUtil.download(bucket, objectName);
		ServletOutputStream output = response.getOutputStream();
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName.substring(objectName.lastIndexOf("/") + 1), "UTF-8"));
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
		IOUtils.copy(stream, output);
	}

	/**
	 * 删除一个文件
	 */
	public AjaxResult deleteFile( String bucket,String objectName) throws Exception {
		minioUtil.deleteObject(bucket, objectName);
		return AjaxResult.success();
	}

	/**
	 * 删除一个桶
	 */
	public AjaxResult deleteBucket(String bucket) throws Exception {
		minioUtil.deleteBucket(bucket);
		return AjaxResult.success();
	}
}
